<template>
  <div>
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区 -->
    <el-card class="box-card">
      <!-- 搜索与添加区域 -->
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="getUserList()">
            <el-button slot="append" icon="el-icon-search" @click="getUserList()"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4"><el-button type="primary" @click="addDialogVisible = true">添加用户</el-button></el-col>
      </el-row>
      <!-- 用户列表区域 -->
      <el-table :data="userList" border stripe>
        <el-table-column type="index"></el-table-column>
        <el-table-column label="姓名" prop="username"></el-table-column>
        <el-table-column label="邮箱" prop="email"></el-table-column>
        <el-table-column label="电话" prop="mobile"></el-table-column>
        <el-table-column label="角色" prop="role_name"></el-table-column>
        <el-table-column label="状态" prop="mg_state">
          //scope.row就代表当前这列的所有数据信息
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state" class="btnSwitch" @change="userStateChanged(scope.row)"> </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180px">
          <template slot-scope="scope">
            <!-- {{ scope.row }} -->
            <!-- 修改按钮 -->
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="modificationBtn(scope.row.id)"></el-button>
            <!-- 删除按钮 -->
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteBtn(scope.row.id)"></el-button>
            <!-- 分配角色按钮 -->
            <el-tooltip class="item" effect="dark" content="分配角色" placement="top" :enterable="false">
              <el-button type="warning" icon="el-icon-setting" size="mini" @click="rights(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>
    <!-- 添加用户对话框 -->
    <el-dialog title="添加用户" :visible.sync="addDialogVisible" width="50%" @close="addOut">
      <!-- 内容主体区 -->
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="80px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addConfirm()">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 添加修改对话框 -->
    <el-dialog title="修改用户" :visible.sync="modifDialogVisible" width="40%" @close="modifOut">
      <!-- 主体区域 -->
      <el-form :model="modifForm" :rules="modifFormRules" ref="modifFormRef" label-width="80px">
        <el-form-item label="用户名">
          <el-input placeholder="请输入内容" :disabled="true" v-model="modifForm.username"> </el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="modifForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="modifForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="modifDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="modifCucceed()">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配角色对话框 -->
    <el-dialog title="分配角色" :visible.sync="rightsDialogVisible" width="50%">
      <div>
        <p>当前的用户：{{ userRole.username }}</p>
        <p>当前的角色：{{ userRole.role_name }}</p>
        <p>
          获取角色信息：
          <el-select v-model="value" placeholder="请选择">
            <el-option v-for="item in roleList" :key="item.id" :label="item.roleName" :value="item.id"> </el-option>
          </el-select>
        </p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="rightsDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="roleSubmit()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    //   邮箱验证规则
    var checkEmail = (rule, value, callback) => {
      const regEmail = /^([a-zA-Z\d])(\w|\-)+@[a-zA-Z\d]+\.[a-zA-Z]{2,4}$/
      if (regEmail.test(value)) {
        return callback()
      }
      return callback(new Error('请输入合法的邮箱'))
    }
    // // 手机号验证规则
    var checkMobile = (rule, value, callback) => {
      const regMobile = /^1(3|4|5|7|8)\d{9}$/
      if (regMobile.test(value)) {
        return callback()
      }
      return callback(new Error('请输入正确的手机号码'))
    }
    return {
      // 获取用户列表参数
      queryInfo: {
        query: '',
        // 当前的页数
        pagenum: 1,
        // 当前每页显示多少条数据
        pagesize: 2
      },
      userList: [],
      total: 0,
      //   控制添加用户对话框隐藏或显示
      addDialogVisible: false,
      // 控制用户修改对话框隐藏或者显示
      modifDialogVisible: false,
      // 分配角色对话框隐藏与显示
      rightsDialogVisible: false,
      //   添加用户表单数据
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      //   添加用户表单验证规则
      addFormRules: {
        username: [
          { required: true, message: '请输入用户名称', trigger: 'blur' },
          { min: 2, max: 5, message: '长度在 2 到 5 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入用户密码', trigger: 'blur' },
          { min: 6, max: 15, message: '请输入6~15位数密码', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱地址', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      // 修改用户信息
      modifForm: {
        username: '',
        email: '',
        mobile: '',
        id: ''
      },
      modifFormRules: {
        email: [
          { required: true, message: '请输入邮箱地址', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      // 被分配角色的用户信息
      userRole: {},
      // 获取到的角色列表
      roleList: [],
      // 已选的角色id
      value: ''
    }
  },
  created() {
    this.getUserList()
  },
  methods: {
    async getUserList() {
      const { data: res } = await this.$http.get('/users', { params: this.queryInfo })
      // 判断请求是否成功
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.userList = res.data.users
      this.total = res.data.total
      //   console.log(res)
    },
    // 监听page-sizes事件改变
    handleSizeChange(newsize) {
      //   console.log(newsize)
      this.queryInfo.pagesize = newsize
      this.getUserList()
    },
    // 监听页码改变事件
    handleCurrentChange(newpage) {
      //   console.log(newpage)
      this.queryInfo.pagenum = newpage
      this.getUserList()
    },
    // 状态按钮发生改变之后同步到后台数据
    async userStateChanged(userInfo) {
      //   console.log(uid, type)
      const { data: res } = await this.$http.put(`users/${userInfo.id}/state/${userInfo.mg_state}`)
      //   console.log(res)
      //   判断请求是否成功
      if (res.meta.status !== 200) {
        userInfo.mg_state = !userInfo.mg_state
        return this.$message.error('更新状态失败')
      }
      this.$message.success('更新用户状态成功')
    },
    // 监听添加对话框的变化事件
    addOut() {
      //   console.log(this.$refs)
      this.$refs.addFormRef.resetFields()
    },
    addConfirm() {
      //   alert(11)
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return
        // 如果通过验证就发送添加用户请求
        const { data: res } = await this.$http.post('users', this.addForm)
        if (res.meta.status !== 201) return this.$message.error('添加失败')
        this.$message.success('添加成功')
        // 隐藏添加对话框
        this.addDialogVisible = false
        // 重新刷新页面
        this.getUserList()
      })
    },
    // 获取修改用户信息
    async modificationBtn(id) {
      this.modifDialogVisible = true
      const { data: res } = await this.$http.get('users/' + id)
      // 判断请求是否成功
      if (res.meta.status !== 200) return this.$message.error('获取用户信息失败')
      // this.$message.success('')
      this.modifForm.username = res.data.username
      this.modifForm.email = res.data.email
      this.modifForm.mobile = res.data.mobile
      this.modifForm.id = res.data.id
      // console.log(res)
    },
    // 监听修改对话框的监听事件
    modifOut() {
      this.$refs.modifFormRef.resetFields()
    },
    // 修改成功调用
    modifCucceed() {
      // console.log(this.modifForm.id)
      const id = this.modifForm.id
      this.$refs.modifFormRef.validate(async valib => {
        if (!valib) return
        // 如果验证成功就发送请求
        const { data: res } = await this.$http.put('users/' + id, this.modifForm)
        if (res.meta.status !== 200) return this.$message.error('修改失败')
        this.$message.success('修改成功')
        // 隐藏修改对话框
        this.modifDialogVisible = false
        // 重新刷新页面
        this.getUserList()
      })
    },
    // 删除用户信息
    async deleteBtn(id) {
      const deleteResult = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      // console.log(deleteResult)
      if (deleteResult !== 'confirm') return this.$message.error('已取消删除')
      // 判断成功就发送请求
      const { data: res } = await this.$http.delete('users/' + id)
      if (res.meta.status !== 200) return this.$message.error('请求发送失败')
      // 提醒用户请求发送成功
      this.$message.success('删除成功')
      // 重新刷新页面
      this.getUserList()
    },
    // 分配角色
    async rights(role) {
      this.userRole = role
      // 在展示对话框之前获取角色列表
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) return this.$message.error('获取角色列表失败')
      // 将数据存储到roleList中
      this.roleList = res.data
      this.rightsDialogVisible = true
    },
    // 提交分配好了的角色
    async roleSubmit() {
      // 如果用户没有选择角色
      if (!this.value) return this.$message.error('请选择要分配的角色')
      // 否则就发送分配用户角色
      const { data: res } = await this.$http.put(`users/${this.userRole.id}/role`, { rid: this.value })
      if (res.meta.status !== 200) return this.$message.errpr('角色设置失败')
      // 提醒用户角色设置成功
      this.$message.success('角色设置成功')
      // 重新刷新页面
      this.getUserList()
      // 隐藏对话框
      this.rightsDialogVisible = false
    }
  }
}
</script>

<style lang="less" scoped></style>
